<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="queryParams" ref="queryFormRef">
        <el-form-item label="投诉人" prop="submitterName">
          <el-input
            v-model="queryParams.submitterName"
            placeholder="请输入投诉人姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="投诉类型" prop="type">
          <el-select
            v-model="queryParams.type"
            placeholder="请选择投诉类型"
            clearable
          >
            <el-option
              v-for="item in complaintTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择处理状态"
            clearable
          >
            <el-option
              v-for="item in complaintStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="提交时间" prop="dateRange">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据统计卡片 -->
    <el-row :gutter="20" class="statistics-row">
      <el-col :span="6">
        <el-card class="statistics-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>待处理投诉</span>
              <el-tag type="danger">{{ statistics.pending }}</el-tag>
            </div>
          </template>
          <div class="card-content">
            <el-progress
              type="dashboard"
              :percentage="statistics.pendingRate"
              :color="pendingColors"
            />
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="statistics-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>处理中</span>
              <el-tag type="warning">{{ statistics.processing }}</el-tag>
            </div>
          </template>
          <div class="card-content">
            <el-progress
              type="dashboard"
              :percentage="statistics.processingRate"
              :color="processingColors"
            />
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="statistics-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>已完成</span>
              <el-tag type="success">{{ statistics.completed }}</el-tag>
            </div>
          </template>
          <div class="card-content">
            <el-progress
              type="dashboard"
              :percentage="statistics.completedRate"
              :color="completedColors"
            />
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="statistics-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>平均处理时间</span>
              <el-tag type="info">{{ statistics.avgProcessTime }}小时</el-tag>
            </div>
          </template>
          <div class="card-content time-chart">
            <el-progress
              :percentage="statistics.timeEfficiency"
              :format="(val) => `效率 ${val}%`"
              :stroke-width="10"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="complaintList"
        border
        style="width: 100%"
      >
        <el-table-column type="expand">
          <template #default="{ row }">
            <div class="detail-content">
              <p><strong>详细描述：</strong>{{ row.description }}</p>
              <p v-if="row.processingRecord">
                <strong>处理记录：</strong>{{ row.processingRecord }}
              </p>
              <div v-if="row.images && row.images.length" class="image-list">
                <strong>相关图片：</strong>
                <el-image
                  v-for="(img, index) in row.images"
                  :key="index"
                  :src="img"
                  :preview-src-list="row.images"
                  fit="cover"
                  class="complaint-image"
                />
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="submitterName" label="投诉人" min-width="120" />
        <el-table-column prop="type" label="投诉类型" width="120">
          <template #default="{ row }">
            {{ getComplaintTypeLabel(row.type) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="title"
          label="投诉标题"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column prop="submitTime" label="提交时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.submitTime) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="处理状态"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getComplaintStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="priority"
          label="优先级"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag :type="getPriorityType(row.priority)">
              {{ getPriorityLabel(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.status !== 'Completed'"
              type="primary"
              link
              :icon="Edit"
              @click="handleProcess(row)"
            >
              处理
            </el-button>
            <el-button
              type="success"
              link
              :icon="View"
              @click="handleViewHistory(row)"
            >
              处理记录
            </el-button>
            <el-button
              v-if="row.status === 'Pending'"
              type="danger"
              link
              :icon="Delete"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNumber"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 处理对话框 -->
    <el-dialog v-model="processDialog.visible" title="处理投诉" width="600px">
      <el-form
        ref="processFormRef"
        :model="processDialog.form"
        :rules="processDialog.rules"
        label-width="100px"
      >
        <el-form-item label="处理状态" prop="status">
          <el-select v-model="processDialog.form.status" style="width: 100%">
            <el-option
              v-for="item in processStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="处理说明" prop="processingRecord">
          <el-input
            v-model="processDialog.form.processingRecord"
            type="textarea"
            :rows="4"
            placeholder="请输入处理说明"
          />
        </el-form-item>
        <el-form-item label="处理人" prop="processor">
          <el-input
            v-model="processDialog.form.processor"
            placeholder="请输入处理人姓名"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="processDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleProcessSubmit"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 处理记录对话框 -->
    <el-dialog v-model="historyDialog.visible" title="处理记录" width="800px">
      <el-timeline>
        <el-timeline-item
          v-for="(history, index) in historyDialog.records"
          :key="index"
          :timestamp="formatDateTime(history.processTime)"
          :type="getTimelineItemType(history.status)"
        >
          <h4>状态更新：{{ getComplaintStatusLabel(history.status) }}</h4>
          <p>处理人：{{ history.processor }}</p>
          <p>处理说明：{{ history.processingRecord }}</p>
        </el-timeline-item>
      </el-timeline>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="historyDialog.visible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Refresh, Edit, Delete, View } from "@element-plus/icons-vue";
import {
  getComplaints,
  processComplaint,
  deleteComplaint,
  getComplaintHistory,
  getComplaintStatistics,
} from "@/api/complaint";

// 投诉类型选项
const complaintTypes = [
  { label: "设施维修", value: "Facility" },
  { label: "环境卫生", value: "Environment" },
  { label: "噪音扰民", value: "Noise" },
  { label: "安全隐患", value: "Security" },
  { label: "其他", value: "Other" },
];

// 投诉状态选项
const complaintStatus = [
  { label: "待处理", value: "Pending" },
  { label: "处理中", value: "Processing" },
  { label: "已完成", value: "Completed" },
  { label: "已关闭", value: "Closed" },
];

// 处理状态选项（不包含待处理）
const processStatus = complaintStatus.filter(
  (item) => item.value !== "Pending"
);

// 优先级选项
const priorities = [
  { label: "低", value: "Low" },
  { label: "中", value: "Medium" },
  { label: "高", value: "High" },
  { label: "紧急", value: "Urgent" },
];

// 查询参数
const queryParams = ref({
  submitterName: "",
  type: "",
  status: "",
  dateRange: [],
  pageNumber: 1,
  pageSize: 10,
});

// 数据相关
const loading = ref(false);
const complaintList = ref([]);
const total = ref(0);
const queryFormRef = ref();

// 统计数据
const statistics = ref({
  pending: 0,
  processing: 0,
  completed: 0,
  pendingRate: 0,
  processingRate: 0,
  completedRate: 0,
  avgProcessTime: 0,
  timeEfficiency: 0,
});

// 进度条颜色配置
const pendingColors = [
  { color: "#f56c6c", percentage: 20 },
  { color: "#e6a23c", percentage: 40 },
  { color: "#5cb87a", percentage: 100 },
];

const processingColors = [
  { color: "#e6a23c", percentage: 40 },
  { color: "#1989fa", percentage: 70 },
  { color: "#5cb87a", percentage: 100 },
];

const completedColors = [{ color: "#5cb87a", percentage: 100 }];

// 处理对话框
const processDialog = reactive({
  visible: false,
  currentComplaint: null,
  form: {
    status: "",
    processingRecord: "",
    processor: "",
  },
  rules: {
    status: [{ required: true, message: "请选择处理状态", trigger: "change" }],
    processingRecord: [
      { required: true, message: "请输入处理说明", trigger: "blur" },
    ],
    processor: [
      { required: true, message: "请输入处理人姓名", trigger: "blur" },
    ],
  },
});

// 处理记录对话框
const historyDialog = reactive({
  visible: false,
  records: [],
});

// 获取投诉列表
const getList = async () => {
  try {
    loading.value = true;
    const [startDate, endDate] = queryParams.value.dateRange || [];
    const params = {
      ...queryParams.value,
      startDate,
      endDate,
    };
    delete params.dateRange;

    const res = await getComplaints(params);
    complaintList.value = res.items;
    total.value = res.total;
  } catch (error) {
    console.error("获取投诉列表失败：", error);
  } finally {
    loading.value = false;
  }
};

// 获取统计数据
const getStatistics = async () => {
  try {
    const res = await getComplaintStatistics();
    statistics.value = res;
  } catch (error) {
    console.error("获取统计数据失败：", error);
  }
};

// 搜索方法
const handleQuery = () => {
  queryParams.value.pageNumber = 1;
  getList();
};

// 重置搜索
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

// 处理投诉
const handleProcess = (row) => {
  processDialog.currentComplaint = row;
  processDialog.form = {
    status: row.status === "Pending" ? "Processing" : row.status,
    processingRecord: "",
    processor: "",
  };
  processDialog.visible = true;
};

// 提交处理
const handleProcessSubmit = async () => {
  try {
    await processComplaint(
      processDialog.currentComplaint.id,
      processDialog.form
    );
    ElMessage.success("处理成功");
    processDialog.visible = false;
    getList();
    getStatistics();
  } catch (error) {
    console.error("处理失败：", error);
  }
};

// 查看处理记录
const handleViewHistory = async (row) => {
  try {
    const res = await getComplaintHistory(row.id);
    historyDialog.records = res;
    historyDialog.visible = true;
  } catch (error) {
    console.error("获取处理记录失败：", error);
  }
};

// 删除投诉
const handleDelete = (row) => {
  ElMessageBox.confirm("确定要删除该投诉记录吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await deleteComplaint(row.id);
      ElMessage.success("删除成功");
      getList();
      getStatistics();
    } catch (error) {
      console.error("删除失败：", error);
    }
  });
};

// 分页方法
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val;
  getList();
};

const handleCurrentChange = (val) => {
  queryParams.value.pageNumber = val;
  getList();
};

// 获取投诉类型标签
const getComplaintTypeLabel = (type) => {
  return complaintTypes.find((item) => item.value === type)?.label || type;
};

// 获取投诉状态标签
const getComplaintStatusLabel = (status) => {
  return complaintStatus.find((item) => item.value === status)?.label || status;
};

// 获取优先级标签
const getPriorityLabel = (priority) => {
  return priorities.find((item) => item.value === priority)?.label || priority;
};

// 获取状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    Pending: "danger",
    Processing: "warning",
    Completed: "success",
    Closed: "info",
  };
  return statusMap[status] || "info";
};

// 获取优先级标签类型
const getPriorityType = (priority) => {
  const priorityMap = {
    Low: "info",
    Medium: "warning",
    High: "danger",
    Urgent: "error",
  };
  return priorityMap[priority] || "info";
};

// 获取时间线项目类型
const getTimelineItemType = (status) => {
  const typeMap = {
    Pending: "danger",
    Processing: "warning",
    Completed: "success",
    Closed: "info",
  };
  return typeMap[status] || "info";
};

// 格式化日期时间
const formatDateTime = (datetime) => {
  if (!datetime) return "-";
  return new Date(datetime).toLocaleString();
};

// 初始化
onMounted(() => {
  getList();
  getStatistics();
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .search-card {
    margin-bottom: 20px;
  }

  .statistics-row {
    margin-bottom: 20px;

    .statistics-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .card-content {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 180px;

        &.time-chart {
          flex-direction: column;
          gap: 20px;
        }
      }
    }
  }

  .table-card {
    .detail-content {
      padding: 20px;

      p {
        margin: 10px 0;
      }

      .image-list {
        margin-top: 10px;

        .complaint-image {
          width: 100px;
          height: 100px;
          margin-right: 10px;
          margin-top: 10px;
          border-radius: 4px;
          cursor: pointer;
        }
      }
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
